package com.openai.chatgpt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.openai.chatgpt.domain.entity.chat.ChatCompletion;
import com.openai.chatgpt.domain.entity.chat.ChatCompletionResponse;
import com.openai.chatgpt.domain.entity.chat.Message;
import com.openai.chatgpt.service.ChatgptService;
import com.openai.chatgpt.utils.ChatGPT;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import com.theokanning.openai.utils.TikTokensUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * chatgpt服务实施
 *
 * @author Amadeus
 * @date 2024/02/17
 */
@Slf4j
@Service
public class ChatgptServiceImpl implements ChatgptService {

    @Autowired
    private ChatGPT customizingChatGPT;
    @Autowired
    private OpenAiService openAiService;

    @Override
    public String chatCompletion(String content) {
        List<Message> messages = new ArrayList<>();
        messages.add(Message.of(content));
        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model(ChatCompletion.Model.GPT_3_5_TURBO.getName())
                .messages(messages)
                .maxTokens(3000)
                .temperature(0.9)
                .build();
        log.info("chatGPT聊天,request:{}", JSONObject.toJSONString(chatCompletion));
        ChatCompletionResponse response = customizingChatGPT.chatCompletion(chatCompletion);
        log.info("chatGPT聊天,response:{}", JSONObject.toJSONString(response));
        Message res = response.getChoices().get(0).getMessage();
        return res.getContent();
    }

    @Override
    public String chatRecommendedCompletion(String content) {
        log.info("Streaming chat completion...");
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.USER.value(), content);
        messages.add(systemMessage);
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
                .builder()
                .model(TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName())
                .messages(messages)
                .n(1)
                .maxTokens(3000)
                .logitBias(new HashMap<>())
                .build();

        ChatCompletionResult chatCompletion = openAiService.createChatCompletion(chatCompletionRequest);
        log.info("JSON:{}", JSON.toJSONString(chatCompletion));
        return chatCompletion.getChoices().get(0).getMessage().getContent();
    }

}
